import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MorningStar {
	
	public static void main(String[] args)
	{
		getCSV("Apple");
		extract_data("Apple");
	}
	
	//==============================================================================================================================================
	public static void extract_data(String cName)
	{

		FileInputStream fstream;
		try 
		{
			fstream = new FileInputStream(cName+".csv");
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null)   
			{
				//System.out.println(strLine);
				if (strLine.contains("Liquidity/Financial Health"))
				{	
					String[] years = strLine.split(","); // Separated by commas
					System.out.println(years[0]);
					System.out.println("YEARS:  \t" + years[1] + "\t" + years[2] + "\t" + years[3]);
				}
				
				if (strLine.contains("Quick Ratio"))
				{
					String[] values_in_line = strLine.split(","); // Separated by commas
					System.out.println("Quick Ratio     " + values_in_line[1] + "\t" + values_in_line[2] + "\t" + values_in_line[3]);
				}
			}
		} 
		catch (Exception e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
	//==============================================================================================================================================
	public static void getCSV(String cName)
	  {
	     try
	     {
	        /*
	         * Get a connection to the URL and start up
	         * a buffered reader.
	         */
	        long startTime = System.currentTimeMillis();
	 
	        System.out.println("Connecting to Morning Star...\n");
	        String ticker=getTicker(cName);
	        if(cName=="")
	        	return;
	        URL url = new URL("http://financials.morningstar.com/ajax/exportKR2CSV.html?t="+ticker);
	        url.openConnection();
	        InputStream reader = url.openStream();
	 
	        /*
	         * Setup a buffered file writer to write
	         * out what we read from the website.
	         */
	        FileOutputStream writer = new FileOutputStream(cName+".csv");
	        byte[] buffer = new byte[153600];
	        int totalBytesRead = 0;
	        int bytesRead = 0;
	 
	        System.out.println("Reading CSV file 150KB blocks at a time.\n");
	 
	        while ((bytesRead = reader.read(buffer)) > 0)
	        {  
	           writer.write(buffer, 0, bytesRead);
	           buffer = new byte[153600];
	           totalBytesRead += bytesRead;
	        }
	 
	        long endTime = System.currentTimeMillis();
	 
	        System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n");
	        writer.close();
	        reader.close();
	     }
	     catch (MalformedURLException e)
	     {
	        e.printStackTrace();
	     }
	     catch (IOException e)
	     {
	        e.printStackTrace();
	     }
	 
	  }
	
	//==============================================================================================================================================
	public static String getTicker(String companyName){
		String ticker="";
		//http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=apple&callback=YAHOO.Finance.SymbolSuggest.ssCallback
		   URL tickerUrl;
		try {
			tickerUrl = new URL("http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=" + companyName + "&callback=YAHOO.Finance.SymbolSuggest.ssCallback");
			URLConnection tickerConn;
			try {
				tickerConn = tickerUrl.openConnection();
				BufferedReader tickerIn = new BufferedReader(new InputStreamReader(tickerConn.getInputStream()));
		        String tempr,tempw="";
		        while((tempr=tickerIn.readLine())!=null){
		        	tempw+=tempr;
		        }
		        String what="\"symbol\":\"";
		        //System.out.println(tempw.indexOf(what));
		        int i=tempw.indexOf(what);
		        if(i>=0)
		        	for(i+=what.length();i<tempw.length();i++)
		        	{
		        		if(tempw.charAt(i)=='"')
		        			break;
		        		ticker+=tempw.charAt(i);
		        	}
			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	          

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
           
				return ticker;
	}
}
